package com.example.myblog.service;

import com.example.myblog.dao.TagMapper;
import com.example.myblog.entity.Tag;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class TagService {

    @Autowired
    private TagMapper tagMapper;
    /**保存*/
    public int save(Tag tag){
        tag.setBlogCount(0);
        tag.setCreateTime(new Date());
        return tagMapper.insertOne(tag);
    }
    /**通过id删除*/
    public int deleteById(Integer id){
        return tagMapper.deleteTagById(id);
    }
    /**通过id查找*/
    public Tag findById(Integer id){
        return tagMapper.findTagById(id);
    }
    /**更新单个tag*/
    public int update(Tag tag){
        return tagMapper.updateTag(tag);
    }
    /**分页查询all*/
    public Page<Tag> pageAll(Integer page){
        PageHelper.startPage(page,3);
        return tagMapper.listTagAll();
    }
    /**查询前num个--list*/
    public List<Tag> listTopNum(Integer num){
        return tagMapper.findTagTopNum(num);
    }
    /**查询所有--list*/
    public List<Tag> list(){
        return tagMapper.findTagAll();
    }
    /**根据ids批量查询*/
    public List<Tag> listByIds(String ids){
        if(ids==null) return null;
        List<String> idList = castToList(ids);
        return tagMapper.findTagByIds(idList);
    }
    /**根据names批量查询*/
    public List<Tag> listByNames(String names){
        if(names==null) return null;
        List<String> nameList = castToList(names);
        return tagMapper.findTagByNames(nameList);
    }
    /**将string转为list*/
    private List<String> castToList(String tNames){
        List<String> tagList = new ArrayList<>();
        if (tNames!=null&&!tNames.equals("")){
            String[] tArr = tNames.split(",");
            tagList.addAll(Arrays.asList(tArr));
        }
        return tagList;
    }
}
